/**
 * 
 */
package main.org.form.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.compiere.dsr.DSR_DataCollection;
import org.compiere.dsr.DSR_ExcelImport;
import org.compiere.model.MAttachmentEntry;
import org.compiere.model.MBPMFormCode;
import org.compiere.process.DSR_GenerateReport;
import org.compiere.process.ProcessInfo;
import org.compiere.util.Env;
import org.joda.time.DateTime;

import extend.org.compiere.utils.Util;


/**
 * @author V.Sokolov
 *
 */
public class DownloadExcelAction extends FormBP {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2020965374760216291L;
	
	private InputStream fileInputStream;
	private String filename;

	public InputStream getFileInputStream() {
		return fileInputStream;
	}
	
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	
	/* 
	 */
	@Override
	public String execute() throws Exception {
		
		MBPMFormCode fCode = new MBPMFormCode(Env.getCtx(), getFormCodeID(), null);
		
		setFilename(getPage()+"_"+fCode.getName());
		
		String nameProcess = DSR_GenerateReport.class.getName();
		int AD_Process_ID = Util.getAD_Process(nameProcess.substring(nameProcess.lastIndexOf(".")+1, nameProcess.length()));
		//  Prepare Process
		ProcessInfo pi = new ProcessInfo ("The recalculate form values", AD_Process_ID);
		//  Prepare Process
		pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
		pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
		
		String path = Util.localFilePath + "pattern" + new DateTime() + ".xls";
		MAttachmentEntry entry = Util.getAttachment(pi, Env.getCtx(), path);
		
		DSR_DataCollection collection = new DSR_DataCollection(getFormID(), getProjectID(), getSubsID());
		File outFile = DSR_ExcelImport.collectionImport(entry, collection);
		
		if(!outFile.exists())
			return NONE;
		
	    fileInputStream = new FileInputStream(outFile);
		
		return SUCCESS;
	}

}
